package example.zxing.templist;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

/**
 * @Created by taylor on 5/30/18.
 * @class desc log system, save log info into custom folders.
 * <p>
 * 1. Log file's name formats in 2018-05-30.txt
 */

public class LogUtils {

    public final static String CK_FOLDER_ROOT_PATH = Environment.getExternalStorageDirectory() + "/0a_TTI_QR_Checker";

    private final static String TAG = "#Log-System#";
    public final static int LOG_TYPE_UPDATE = 0;
    public final static int LOG_TYPE_CRASH = 1;
    public final static int LOG_TYPE_DB_ERROR = 2;

    private static Context mContext;
    private final static String FORMAT_PATTERN_FILE_NAME = "yyyyMMdd_HH:mm:ss";
    private final static String FORMAT_PATTERN_TIEMSTAMP = "yyyy-MM-dd HH:mm:ss";
    private final static String LOG_FILE_SUFFIX = ".txt";
    public final static String CK_LOG_DIVIDER_LINE = "**********************************";

    private static SimpleDateFormat dateFormat = new SimpleDateFormat(FORMAT_PATTERN_FILE_NAME, Locale.CHINA);
    private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat(FORMAT_PATTERN_TIEMSTAMP, Locale.CHINA);

    public static String CURRENT_INPUT_FILE = ""; // "": 退出扫描    有文件名:则追加添加文本。

    /**
     * Check and Create all the log folders.
     */
    public static void init(Context c) {
        mContext = c;
        createDirectory(new File(CK_FOLDER_ROOT_PATH));
    }

    /**
     * Append log diray into relative log file
     */
    public static void appendPieceOfLog(String addInfo) {
        try {
            fWriter.write("\n" + addInfo +
                    "\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
//        finally {
//            try {
//                if (fWriter != null) {
//                    fWriter.close();
//                }
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

    private static File mainFile;
    private static FileWriter fWriter;

    /**
     * start scan
     */
    public static String LaunchANewLogFile() {
        CURRENT_INPUT_FILE = getTodayLogFileName();
        mainFile = getTodayLogFile(CK_FOLDER_ROOT_PATH, CURRENT_INPUT_FILE);
        try {
            fWriter = new FileWriter(mainFile, true);  // 以追加形式
        } catch (Exception e) {
            e.printStackTrace();
        }
        return CK_FOLDER_ROOT_PATH + CURRENT_INPUT_FILE;
    }

    /**
     * quit scan
     */
    public static void CloseCurrentLogFile() {
        CURRENT_INPUT_FILE = "";
        try {
            if (fWriter != null) {
                fWriter.close();
            }
            mainFile = null;
            fWriter = null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * Delete all the files and folders.
     */
    public static void deleteAll() {
//        Log.e(TAG, (justDelete(CK_FOLDER_NEW_APK_PATH) ? "Y" : "N") + "--> apk");
//        Log.e(TAG, (justDelete(CK_LOG_UPDATE_PATH) ? "Y" : "N") + "--> log-update");
//        Log.e(TAG, (justDelete(CK_LOG_CRASH_PATH) ? "Y" : "N") + "--> log-crash");
//        Log.e(TAG, (justDelete(CK_LOG_DB_ERROR_PATH) ? "Y" : "N") + "--> log-db");
    }

    public static boolean justDelete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            Log.d(TAG, "delete single file failed [" + fileName + "] not exists.");
            return false;
        } else {
            if (file.isFile())
                return deleteFile(fileName);
            else
                return deleteDirectory(fileName);
        }
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Log.d(TAG, "delete single file " + fileName + "successfully");
                return true;
            } else {
                Log.d(TAG, "delete single file " + fileName + "failed");
                return false;
            }
        } else {
            Log.d(TAG, "delete single file failed [" + fileName + "] not exists.");
            return false;
        }
    }

    /**
     * 删除目录及目录下的文件
     *
     * @param dir 要删除的目录的文件路径
     * @return 目录删除成功返回true，否则返回false
     */
    public static boolean deleteDirectory(String dir) {
        // 如果dir不以文件分隔符结尾，自动添加文件分隔符
        if (!dir.endsWith(File.separator))
            dir = dir + File.separator;
        File dirFile = new File(dir);
        // 如果dir对应的文件不存在，或者不是一个目录，则退出
        if ((!dirFile.exists()) || (!dirFile.isDirectory())) {
            Log.d(TAG, "delete dir failed [" + dir + "] not exists.");
            return false;
        }
        boolean flag = true;
        // delete all children files and folders
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {  // delete child file
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag)
                    break;
            } else if (files[i].isDirectory()) {  // delete child dir
                flag = deleteDirectory(files[i]
                        .getAbsolutePath());
                if (!flag)
                    break;
            }
        }
        if (!flag) {
            Log.d(TAG, "deleteDirectory Failed.");
            return false;
        }
        // 删除当前目录
        if (dirFile.delete()) {
            Log.d(TAG, "deleteDirectory [" + dir + "] successfully!");
            return true;
        } else {
            return false;
        }
    }

    /**
     * 判断文件夹是否存在，if not creates it.
     */
    public static void createDirectory(File file) {
        if (file.exists()) {
            if (file.isDirectory()) {
                Log.d(TAG, "dir exists-->" + file.getAbsolutePath());
            } else {
                Log.d(TAG, "the same name file exists-->" + file.getAbsolutePath());
            }
        } else {
            boolean bMkDir = file.mkdir();
            Log.d(TAG, "dir[" + file.getAbsolutePath() + "] not exists, create it ... " + (bMkDir ? "success" : "fail"));
        }
    }

    /**
     * Get today's [xxxx-xx-xx.txt] log file name
     * eg. ttiQRScan_20180530_11:22:33.txt
     */
    public static String getTodayLogFileName() {
        StringBuffer sb = new StringBuffer("");
//        sb.append("ttiQRScan_");
        sb.append(dateFormat.format(Calendar.getInstance(Locale.CHINA).getTime()));
        sb.append(LOG_FILE_SUFFIX);
//        Log.i(TAG, "CurrentLogFileName-->" + sb.toString());
        return sb.toString();
    }

    /**
     * Get today's [xxxx-xx-xx.txt] log file.
     */
    public static File getTodayLogFile(String fullPath, String fileName) {
        File file;
        if (fullPath.charAt(fullPath.length() - 1) == '/') {
            file = new File(fullPath + fileName);
        } else {
            file = new File(fullPath + "/" + fileName);
        }
        if (!file.exists()) {
            if (!new File(fullPath).exists()) {
                boolean bte = new File(fullPath).mkdir();
                Log.d(TAG, fullPath + " re-mkdir ??!!--> " + (bte ? "Y" : "N"));
            }
            try {
                if (file.createNewFile()) {
                    Log.e(TAG, "createNewFile--> " + fileName + " Y");
                } else {
                    Log.e(TAG, "createNewFile--> " + fileName + " N");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }

}
